#!/usr/bin/env python3

from ResultWinGUI import ResultWin
import os
import sys
import yaml

if __name__ == "__main__":
    bag_path = ""
    params = {}
    if len(sys.argv) >= 2 and not sys.argv[1] == None:
        bag_folder = sys.argv[1]
        if os.path.exists(bag_folder) == False:
            print(f"{bag_folder} not exist.")
            sys.exit()
        bag_files = [
            os.path.join(bag_folder, file)
            for file in os.listdir(bag_folder)  # noqa
            if file.endswith(".bag")
        ]
        bag_files = sorted(bag_files, key=lambda x: os.path.getctime(x), reverse=True)
        if bag_files == []:
            print(f"No bag files in {bag_folder}.")
            sys.exit()
        bag_path = bag_files[0]
        param_yaml = bag_path.split(".bag")[0] + "_param.yaml"
        if os.path.exists(param_yaml):
            params = yaml.load(open(param_yaml, "r"), Loader=yaml.FullLoader)
        os.remove(param_yaml)
    result_win = ResultWin(bag_path, params)
    result_win.mainloop()
    sys.exit()
